golang object pool

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package main

import (
"log"
"time"
)

func main() {

size := (1 << 23)

start := time.Now()
for i := 0; i < size; i++ {
data := make([]byte, 0, (1 << 15))
_ = data
}

d := time.Now().Sub(start)
log.Println("without pool", d)

}

add bytes pool

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
type bytePool struct {
c chan []byte
width int
}

func NewBytePool(size, width int) (bp *bytePool) {
return &bytePool{
c: make(chan []byte, size),
width: width,
}
}

func (bp *bytePool) Get() (b []byte) {
select {
case b = <-bp.c:
//do nothing

default:
b = make([]byte, 0, bp.width)

}
return
}

func (bp *bytePool) Put(b []byte) {
select {
case bp.c <- b:
//return back
default:
//discard bytes
}
return
}

the code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package main

import (
"log"
"time"
)

func main() {

size := (1 << 23)

start := time.Now()
for i := 0; i < size; i++ {
data := make([]byte, 0, (1 << 15))
_ = data
}

d := time.Now().Sub(start)
log.Println("without pool", d)

bp := NewBytePool((1 << 20), (1 << 15))

start = time.Now()
for i := 0; i < size; i++ {
data := bp.Get()
_ = data
bp.Put(data)
}

d = time.Now().Sub(start)
log.Println("with pool", d, getc, newc)

}
// 2018/04/24 18:37:21 without pool 8.784228302s
// 2018/04/24 18:37:22 with pool 713.31206ms